<template>
  <div class="crm-relative-table">
    <flexbox v-if="config.showHeader" class="header" justify="center">
      <el-input :placeholder="config.placeholder" v-model="search" @keyup.enter="searchInput">
        <template v-slot:append>
          <el-button type="primary" @click="searchInput">搜索</el-button>
        </template>
      </el-input>
    </flexbox>
    <div class="body">
      <el-table
          v-loading="loading"
          id="crm-table"
          ref="refCrmTable"
          :row-height="40"
          :data="list"
          :height="tableHeight + reduceHeaderHeight"
          :row-key="config.rowKey"
          class="n-table--border"
          use-virtual
          stripe
          border
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            show-overflow-tooltip
            reserve-selection
            type="selection"
            align="center"
            width="55"/>
        <el-table-column v-for="(item, index) in fieldList" :key="index"
                         :fixed="index==0"
                         :prop="item.fieldName"
                         :label="item.name"
                         :formatter="config.tableFormatter"
                         show-overflow-tooltip/>
      </el-table>
      <div class="p-container">
        <el-pagination
            :current-page="currentPage"
            :total="total"
            :page-size="pageSize"
            :pager-count="5"
            class="p-bar"
            background
            layout="total, prev, pager, next"
            @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from "vue"
import merge from "utils/merge";
import {isArray} from '/src/utils/types.js'

const DefaultCrmRelativeTable = {
  // 表头
  fieldList: null,
  request: null,
  params: null,
  placeholder: '', // 搜索placeholder
  isPaging: true, // 是否分页
  showHeader: true, //
  tableFormatter: null,
  rowKey: '' // ElTable的rowKey
}

// 引入消息总线
const cxt  = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus

defineOptions({
  // 通用table
  name: 'CrmRelativeTable',
})
const props = defineProps({
  props: Object
})

const emits = defineEmits(['selection-change'])

const search = ref('')
const copySearch = ref('')
const tableHeight = ref(doument.documentElement.clientHeight - 320)
const loading = ref(false) // 加载动画
const list = ref([])
const fieldList = ref([])
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)
const selectionList = ref([])


const config = computed(() => {
  return merge({...DefaultCrmRelativeTable}, props.props || {})
})

const reduceHeaderHeight = computed(() => {
  return config.value.showHeader ? 0 : 32
})

function created() {
  if (config.value.fieldList) {
    fieldList.value = config.value.fieldList
  }
  getList()
}
created();

onMounted(() => {
  updateTableHeight()
  window.onresize = () => {
    updateTableHeight()
  }
})

/**
 * 进行搜索操作
 */
function searchInput() {
  copySearch.value = search.value
  handleCurrentChange(1)
}

/**
 * 更改当前页数
 * @param {*} val
 */
function handleCurrentChange(val) {
  currentPage.value = val
  getList()
}

/**
 * 获取列表
 */
function getList() {
  config.value.request(config.value.params || {}).then(res => {
    const resData = res.data.data
    if (isArray(resData)) {
      total.value = resData.length
      list.value = resData
    } else {
      list.value = resData.list
      total.value = resData.totalRow
    }
  }).catch(() => {

  })
}

/**
 * 更新表高
 */
function updateTableHeight() {
  tableHeight.value = document.documentElement.clientHeight - 320
}

/**
 * 获取table
 */
function getMainTable() {
  console.log("getMainTable", getMainTable)
  let table = null
  table = cxt.refs.refCrmTable
  // this.$children.forEach(item => {
  //   if (item.$options && item.$options.name === 'ElTable') {
  //     console.log("table", item)
  //     table = item
  //   }
  // })
  console.log("table", table)
  return table
}

/**
 * 勾选操作
 * @param {*} val
 */
function handleSelectionChange(val) {
  // 单选操作
  if (config.value.radio && val.length > 1) {
    getMainTable().clearSelection()
    const lastObj = val[val.length - 1]
    getMainTable().toggleRowSelection(lastObj)
    selectionList.value = [lastObj]
  } else {
    selectionList.value = val
  }
  emits('selection-change', val)
}

</script>


<style lang="scss" scoped>
.crm-relative-table {
  .header {
    :deep( .el-input) {
      width: 300px;
    }

    :deep( .el-input-group__append ) {
      background-color: $xr-color-primary;
      border-color: $xr-color-primary;
      color: white;
    }
  }

  .body {
    margin-top: 15px;
    border-top: 1px solid #e6e6e6;
  }
}
</style>
